package com.ctgu.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctgu.server.components.config.AsyncConfiguration;
import com.ctgu.server.dao.constant.CacheKey;
import com.ctgu.server.dao.dto.FormUserDto;
import com.ctgu.server.dao.dto.FromDto;
import com.ctgu.server.dao.entity.*;
import com.ctgu.server.dao.vo.Result;
import com.ctgu.server.mapper.FormMapper;
import com.ctgu.server.service.FormService;
import com.ctgu.server.utils.ResultUtil;
import com.github.dozermapper.core.Mapper;
import lombok.extern.slf4j.Slf4j;
import net.oschina.j2cache.CacheChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.List;
import java.util.Random;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ctgu
 * @since 2023-05-17
 */
@Service
@Slf4j
public class FormServiceImpl extends ServiceImpl<FormMapper, Form> implements FormService {
    @Qualifier("asyncExecutor")
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Autowired
    private FormMapper formMapper;

    @Autowired
    private CacheChannel cacheChannel;

    @Autowired
    private PlatformTransactionManager transactionManager;
    @Autowired
    private GroupUserServiceImpl groupUserService;
    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private FormHistoryServiceImpl formHistoryService;
    @Autowired
    private FormGroupServiceImpl formGroupService;

    @Autowired
    private GroupServiceImpl groupService;

    @Autowired
    private Mapper mapper;

    @Override
    public Result deleteForm(String userId, Long formId) {
        Form form=this.getById(formId);
        if(form==null||!form.getUserId().equals(userId)){
            return ResultUtil.error("参数错误，或者用户无权限操作");
        }

        //删除表单信息
        threadPoolTaskExecutor.execute(()->{
            deleteFroupInfo(formId);
        } );

        return ResultUtil.success("操作成功");
    }

    @Override
    public Result userApplyForm(FormUserDto formUserDto) {
        //1.查询对应的表单是否存在
        Form form=(Form) cacheChannel.get(CacheKey.Form_Redis, formUserDto.getFormId()).getValue();
        if(form==null){
            form=this.getById(formUserDto.getFormId());
            cacheChannel.set(CacheKey.Form_Redis, formUserDto.getFormId(),form);
        }
        if(form==null||(form.getUserLimit()!=0&&form.getUserLimit()>=form.getUserCount())){
            return ResultUtil.error("未查询到目标组织！报名人数已达到上限！");
        }
        //2.检查报名人是否有报名资格
        LambdaQueryWrapper<FormGroup> formGroupLambdaQueryWrapper=new LambdaQueryWrapper<>();
        formGroupLambdaQueryWrapper.eq(FormGroup::getFormId,form.getId());
        List<FormGroup> formGroupList= formGroupService.list(formGroupLambdaQueryWrapper);
        //3.formGroupList==null则表示允许任意人报名
        if(formGroupList.size()!=0){
            User user= userService.getById(formUserDto.getUserId());
            if(user==null){
                return ResultUtil.error("未查询到该用户");
            }
            boolean flag=true;
            for(FormGroup formGroup:formGroupList){
                LambdaQueryWrapper<GroupUser> groupUserLambdaQueryWrapper=new LambdaQueryWrapper<>();
                groupUserLambdaQueryWrapper
                        .eq(GroupUser::getGroupId,formGroup.getGroupId())
                        .eq(GroupUser::getUserId,formUserDto.getUserId());
                if(groupUserService.count(groupUserLambdaQueryWrapper)!=0){
                    flag=false;
                    break;
                }
            }
            if(flag){
                return ResultUtil.error("用户不在范围内！");
            }
        }
        //4.乐观锁实现
        FormHistory formHistory=mapper.map(formUserDto,FormHistory.class);
        TransactionTemplate transactionTemplate=new TransactionTemplate(transactionManager);
        Form finalForm = form;
        Boolean isSuccess= transactionTemplate.execute(status -> {
                formMapper.applyUserToForm(formUserDto.getFormId(), finalForm.getVersion());
                int count=1;
                for(String groupId:formUserDto.getGroupIdList()){
                    formHistory.setIndex(count);
                    formHistory.setGroupId(groupId);
                    formHistoryService.save(formHistory);
                    count++;
                }
//                for(int i=0;i<formUserDto.getGroupIdList().size();i++){
//
//                    formHistoryService.save(formHistory);
//                }
//                formHistoryService.save(formHistory);
            return true;
        });
       if(Boolean.FALSE.equals(isSuccess)){
           return ResultUtil.error("报名失败");
       }
        return ResultUtil.success("成功报名");
    }

    @Override
    public Result getUserCrateList(String userId) {
        userService.selectUser(userId);
        if(userId==null){
            return ResultUtil.error("用户ID不存在");
        }
        //查询用户创建的表单
        LambdaQueryWrapper<Form> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Form::getUserId,userId);
        //返回用户表单列表
        return ResultUtil.success(this.list(lambdaQueryWrapper));
    }

//    @Override
//    public Result getUserApplyList(String userId) {
//        userService.selectUser(userId);
//        if(userId==null){
//            return ResultUtil.error("用户ID不存在");
//        }
//        LambdaQueryWrapper<us>
//    }

    @Transactional
    public void deleteFroupInfo(Long formId){
        formHistoryService.removeById(formId);
        formGroupService.removeById(formId);
        this.removeById(formId);
    }
//    @Async("asyncExecutor")
//    public void testasyncMethod(){
//        try {
//            int i = new Random().nextInt(10000);
//            log.info("syncServiceImpl.syncTest.随机睡眠:{}毫秒", i);
//            Thread.sleep(i);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    @Override
    public Result getUserFormList(String id) {
        //1.查询用户是否存在
        User user= userService.selectUser(id);
        if(user==null){
            return ResultUtil.error("未查询到该用户");
        }
        List<Form> formIdList= formMapper.selectForms(id);

//        //2.用户存在时查询所有当前用户参与的报名表
//        List<FormHistory> formHistoryList= formHistoryService.selectByUserId(id);
//
//        LambdaQueryWrapper<Form> lambdaQueryWrapper=new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(Form::getScope,null);

//         formHistoryList.addAll()
        return ResultUtil.success(formIdList);
    }

    @Override
    @Transactional  //开启事务
    public Result createForm(FromDto fromDto) {
        //1,查询用户是否有重复的表单

       Form form=selectForm(fromDto);
       if(form!=null){
           //查询到重复表单
           return ResultUtil.error("查询到该用户已经存在相同标题的表单");
       }
        //1.创建表单
        //查询当前组织是否存在
        List<String> list=fromDto.getGroupList();

        if(list!=null){
            LambdaQueryWrapper<Group> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.in(Group::getGroupId,list);
            if(groupService.count(lambdaQueryWrapper)!=list.size()){
                return ResultUtil.error("当前组织不存在！");
            }
        }
        form = mapper.map(fromDto, Form.class);
        if(!this.save(form)){
             log.error("数据插入数据库失败");
             return ResultUtil.error("业务繁忙请稍后再试");
         }



        if(list!=null){
            for(String groupId :list){
                FormGroup formGroup=new FormGroup();
                formGroup.setFormId(form.getId());
                formGroup.setGroupId(groupId);
                formGroupService.save(formGroup);
            }
        }

        //删除表单列表缓存
        cacheChannel.evict(CacheKey.Form_Redis,"list");
        return ResultUtil.success(form);
    }


    /**
     * @param fromDto:
     * @return Form
     * @author kvzjj
     * @description TODO 查询用户的表单
     * @date 2023/6/6 14:57
     */
    public Form selectForm(FromDto fromDto){
        LambdaQueryWrapper<Form> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper
                .eq(Form::getUserId,fromDto.getUserId())
                .eq(Form::getTitle,fromDto.getTitle());
        return this.getOne(lambdaQueryWrapper,false);
    }

}
